package com.cjhedu.web.service.impl;

import com.cjhedu.web.domain.Emp;
import com.cjhedu.web.domain.PageBean;
import com.cjhedu.web.dto.EmpDto;
import com.cjhedu.web.dto.EmpLogDto;
import com.cjhedu.web.mapper.EmpMapper;
import com.cjhedu.web.service.EmpService;
import com.cjhedu.web.utils.MyJwtUtils;
import com.cjhedu.web.utils.MyResponseResult;
import com.cjhedu.web.utils.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈佳豪
 * @version 1.0
 */
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private MyJwtUtils myJwtUtils;

    //使用分页插件之后的代码(带条件)
    @Override
    public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize, EmpDto empDto) {
        PageHelper.startPage(pageNum,pageSize);
        Page<Emp> byPage = (Page<Emp>)empMapper.getByPage(empDto);
        return new PageBean<Emp>(byPage.getTotal(),byPage.getResult());

    }

    //根据id删除/批量删除
    @Override
    public int del(Integer[] ids) {
        return empMapper.del(ids);
    }

    @Override
    public int update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        return empMapper.update(emp);
    }

    //修改回显
    @Override
    public Emp getById(Integer id) {
       return empMapper.getById(id);
    }

    //员工登录
    @Override
    public MyResponseResult<String> login(EmpLogDto empLogDto) {
        Emp emp = empMapper.login(empLogDto);
        if (emp == null){
           return MyResponseResult.error("用户名或密码错误");
        }
        //获取员工对象姓名 id 生成jwt
        Map<String, Object> map = new HashMap<>();
        map.put("id",emp.getId());
        map.put("name",emp.getName());
        String jwt = myJwtUtils.createJwt(map);
        return MyResponseResult.ok("生成的JWT:"+ jwt);
    }

    @Override
    public int addEmp(Emp emp) {
        emp.setPassword("111111");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        return empMapper.addEmp(emp);
    }

    //使用分页插件之后的代码(不带条件)
    //@Override
    //public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize) {
    //    PageHelper.startPage(pageNum,pageSize);
    //    Page<Emp> byPage = (Page<Emp>)empMapper.getByPage();
    //    return new PageBean<Emp>(byPage.getTotal(),byPage.getResult());
    //}





    //@Override
    //没有使用分页插件之前的代码
    //public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize) {
    //    Integer start = (pageNum-1)*pageSize;
    //    List<Emp> emps = empMapper.getByPage(start, pageSize);
    //    Long total = empMapper.getTotal();
    //
    //    return new PageBean<>(total,emps);
    //}

    //@Override
    //public Long getTotal() {
    //    return null;
    //}
}
